package com.base.controller;

import com.base.bean.RespBean;
import com.base.bean.User;
import com.base.service.UserService;
import com.common.FTPUtil;
import com.common.OPConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.security.Principal;
import java.util.List;


@RestController
@RequestMapping("/system/hr")
public class SystemUserController {
    @Autowired
    UserService hrService;
    @Autowired
    Environment env;

    @RequestMapping("/id/{hrId}")
    public User getHrById(@PathVariable Long hrId) {
        return hrService.getHrById(hrId);
    }

    @RequestMapping(value = "/{hrId}", method = RequestMethod.DELETE)
    public RespBean deleteHr(@PathVariable Long hrId) {
        if (hrService.deleteHr(hrId) == 1) {
            return new RespBean("success", "删除成功!");
        }
        return new RespBean("error", "删除失败!");
    }

    @RequestMapping(value = "/getByUserId/{id}", method = RequestMethod.GET)
    public User getByUserId(@PathVariable Long id) {
        return hrService.getByUserId(id);
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public RespBean addUser(User user) {
        if (hrService.addUser(user) == 1) {
            return new RespBean("success", "保存成功!");
        }
        return new RespBean("error", "保存失败!");
    }

    @RequestMapping(value = "/", method = RequestMethod.PUT)
    public RespBean updateHr(User hr) {
        if (hrService.updateHr(hr) == 1) {
            return new RespBean("success", "更新成功!");
        }
        return new RespBean("error", "更新失败!");
    }

    @RequestMapping(value = "/resetPassword/{userId}", method = RequestMethod.PUT)
    public RespBean resetPassword(@PathVariable Long userId) {
        if (hrService.resetPassword(userId) == 1) {
            return new RespBean("success", "密码重置成功!");
        }
        return new RespBean("error", "密码重置失败!");
    }

    @RequestMapping(value = "/roles", method = RequestMethod.PUT)
    public RespBean updateHrRoles(Long hrId, Long[] rids) {
        if (hrService.updateHrRoles(hrId, rids) == rids.length) {
            return new RespBean("success", "更新成功!");
        }
        return new RespBean("error", "更新失败!");
    }

    @RequestMapping("/keywords")
    public List<User> getHrsByKeywords(String keywords, Integer start, Integer pageSize) {
        List<User> hrs = hrService.getHrsByKeywords(keywords, start, pageSize);
        return hrs;
    }

    @RequestMapping("/getHrsByKeywordsCount/{keywords}")
    public Integer getHrsByKeywordsCount(@PathVariable(required = false) String keywords) {
        return hrService.getHrsByKeywordsCount(keywords);
    }



    @RequestMapping(value = "/hr/reg", method = RequestMethod.POST)
    public RespBean hrReg(String username, String password) {
        int i = hrService.hrReg(username, password);
        if (i == 1) {
            return new RespBean("success", "注册成功!");
        } else if (i == -1) {
            return new RespBean("error", "用户名重复，注册失败!");
        }
        return new RespBean("error", "注册失败!");
    }

    @RequestMapping(value = "/uploadHead", method = RequestMethod.POST)
    public RespBean uploadHead(MultipartFile file, Long id) throws Exception {
        //获取跟目录
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if(!path.exists()) {
            path = new File("");
        }
        String fileName = id + "_" + System.currentTimeMillis() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
        String urlPath = OPConst.HEAD_DOMAIN.getValue() + env.getProperty("ftp.rootPath") + "img/" + fileName;
        FTPUtil.getInstance(env).uploadFile(env.getProperty("ftp.rootPath") + "img/" , fileName, file.getInputStream());
        User user = new User();
        user.setId(id);
        user.setUserface(urlPath);
        hrService.updateHr(user);
        return new RespBean("success", "头像上传成功!", urlPath);
    }

    @RequestMapping(value = "/changePwd")
    public RespBean changePwd(Principal principal, String password, String newpass) {
        User userPwd = (User)((UsernamePasswordAuthenticationToken) principal).getPrincipal();
        int i = 0;
        Long id = userPwd.getId();
        String userpwd  = userPwd.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean pwd = encoder.matches(password,userpwd);
        if (pwd){
            i = hrService.changePwd(newpass,id);
        }
        if (i == 1) {
            return new RespBean("success", "修改成功!");
        } else {
            return new RespBean("error", "修改失败!");
        }
    }
}
